package java_collection.iterator;

import java.util.ArrayList;
import java.util.Iterator;

public class ConcurrentModificationTest {

	public static void main(String[] args) {
		ArrayList<Integer> list1 = new ArrayList<>();
		ArrayList<Integer> list2 = new ArrayList<>();
		ArrayList<Integer> list3 = new ArrayList<>();
		
		// add 1- 10 in list
		for (int i=1; i <= 10; i++) {
			list1.add(i);
			list2.add(i);
			list3.add(i);
		}
		
		// Error: for each doesn't give you access to iterator
		// you need to call remove on the iterator
		
		// Delete even values
		/*for (Integer i: list){
			if (i%2 == 0) {
				list.remove(i);
				// java.util.ConcurrentModificationException
			}
		}*/
		
		
		System.out.println("there are 3 possible ways to remove values from List");
		
		remove1(list1);
		remove2(list2);
		remove3(list3);
	}
	
	private static void print(ArrayList<Integer> list){
		// Print list values
		System.out.print("List: ");
		for (Integer i: list){
			System.out.print(i + " ");
		}
		System.out.print("\n");
	}
	
	private static void remove1 (ArrayList<Integer> list){
		// Option 1, use for loop
		// Delete even values
		System.out.println("********** Using for loop **********");
		
		for (int i = 0; i < list.size(); i++){
			if (list.get(i)%2 == 0) {
				list.remove(i);
			}
		}
		
		print(list);
	}
	
	private static void remove2 (ArrayList<Integer> list){
		// option 2, using Iterator
		// Delete even values
		System.out.println("********* Using Iterator ***********");
		
		Iterator<Integer> i = list.iterator();
		while(i.hasNext()){
			if ((i.next()%2) == 0) {
				i.remove();
			}
		}
		
		print(list);
	}
	
	private static void remove3 (ArrayList<Integer> list){
		// option 3, using another list
		// Delete even values
		System.out.println("******** Using another list *********");
		
		ArrayList<Integer> selection = new ArrayList<>();
		
		for (Integer i: list){
			if ((i%2) == 0) {
				selection.add(i);
			}
		}
		
		list.removeAll(selection);
		
	}

}
